<?php


namespace App\Http\Controllers;


use App\Http\Requests\Product\ChangeUserRequest;
use App\Models\PartitionAdjustmentAmount;
use App\Models\ProductOrder;
use App\Services\Java\ApiService;
use D1M\Common\Helpers\Result;
use Illuminate\Http\Request;

class ProductController
{

    /**
     * 零售单绑定用户
     * @param ChangeUserRequest $request
     * @return array
     */
    public function changeUser(ChangeUserRequest $request)
    {
        $data = $request->only(['product_order_no','manage_no']);
        $where = ['product_order_no'=>$data['product_order_no']];
        $existInfo = ProductOrder::where($where)->first(['id','manage_no']);

        if(!$existInfo){
            ProductOrder::insert($data);
        }else{
            if($existInfo->manage_no!=$data['manage_no']){
                ProductOrder::where($where)->update(['manage_no'=>$data['manage_no']]);
            }
        }
        return Result::success(null,'保存成功');
    }

    /**
     * 零售单详情(用户+详情+优惠券+调整金额)
     * @param Request $request
     * @param ApiService $api
     * @return array
     */
    public function productOrderDetail(Request $request,ApiService $api)
    {
        $productOrderNo = $request->post('product_order_no');
        $user = $coupon = $adjustment = [];
        $existInfo = ProductOrder::where('product_order_no',$productOrderNo)->first(['id','manage_no']);
        if($existInfo && $existInfo->manage_no) {
            $user = $api->requestJava('/auth/api/user/userInfoByManageNo',
                ['manageNo'=>$existInfo->manage_no],'post');
        }
        $order = $api->requestJava('/product/api/product/retail-order-detail',['orderNo'=>$productOrderNo],'post');

        //调整金额相关
//        $reduceAmount = PartitionAdjustmentAmount::where(['order_no'=>$productOrderNo,'order_type'=>1])
//            ->orderBy('id','desc')
//            ->get(['order_no','manage_no','login_name','init_amount','after_amount','reduce_id','reduce_amount','reduce_description','adjustment_type'])
//            ->toArray();
        //dump($reduceAmount);

//        foreach ($reduceAmount as $v)
//        {
//            if($v['adjustment_type']==0)array_push($coupon,$v);
//            if($v['adjustment_type']==1)array_push($adjustment,$v);
//        }

        $res = [
            'user'=>$user,
            'order'=>$order,
//            'coupon'=>$coupon,
//            'adjustment'=>$adjustment
        ];

        return Result::success($res);
    }


}